#include "project/initialization.h"

PlyBarycenterCoords *
getPlyBarycenterCoords(int num_vertices, Vertex** vlist)
{
	register int i;
	PlyBarycenterCoords* barycenter_coords = (PlyBarycenterCoords *) calloc (1, sizeof(PlyBarycenterCoords));

	if (!barycenter_coords)
	{
		fprintf(stderr, "getPlyBarycenterCoords: error allocating memory for barycenter coords structure\n");
		exit(-1);
	}  

	for (i = 0; i < num_vertices; i++)
	{
		barycenter_coords->xm += vlist[i]->x;
		barycenter_coords->ym += vlist[i]->y;
		barycenter_coords->zm += vlist[i]->z;
	}
	barycenter_coords->xm /= i;
	barycenter_coords->ym /= i;
	barycenter_coords->zm /= i;

	return barycenter_coords;	
}

void
setPlyModelID(PlyModel* ply_model)
{
	ply_model->id = next_ply_model_id;

	next_ply_model_id++;
}

PlyModel*
initPly(char* scene_name, char* file_name)
{
	PlyModel* ply_model = (PlyModel *) calloc (1, sizeof(PlyModel));

	if (!ply_model)
	{
		fprintf(stderr, "initPly: error allocating memory for ply model structure\n");
		exit(-1);
	}  

	loadPly(file_name, &ply_model->num_vertices, &ply_model->num_faces, &ply_model->vlist, &ply_model->flist);

	ply_model->file_name = file_name;
	ply_model->scene_name = scene_name;
	ply_model->bc_coords = getPlyBarycenterCoords( ply_model->num_vertices, ply_model->vlist );
	setPlyModelID(ply_model);

	showPlyInfo(ply_model);

	return ply_model;	
}

void
showPlyInfo(PlyModel* ply_model)
{
	// Mostra (no terminal) informacoes sobre modelos carregados

	printf("\n");
	printf("                  Nome do arquivo PLY: %s\n", ply_model->file_name);
	printf("           Nome do objeto PLY na cena: %s\n", ply_model->scene_name);
	printf("             ID do objeto PLY na cena: %d\n", ply_model->id);
	printf("                   Numero de vertices: %d\n", ply_model->num_vertices);
	printf("                      Numero de faces: %d\n", ply_model->num_faces);

	printf("                      X do Baricentro: %f\n", ply_model->bc_coords->xm);
	printf("                      Y do Baricentro: %f\n", ply_model->bc_coords->ym);
	printf("                      Z do Baricentro: %f\n", ply_model->bc_coords->zm);
	printf("\n");
}

